package test.test_7_4;

import java.util.Objects;

/*
equals方法语法编程练习题
定义一个Animal类
成员变量：
int age,String name,double price
手写它的equals方法，比较getClass和instanceof的区别?
    instanceof比较的是继承关系或者实现关系的类类型,子类对象或者实现类对象放在前面；
    而getClass得到的是确切的类型，并不考虑继承，它判断的是引用指向的对象的类型，与声明该变量的类型无关
 */
public class Demo01 {
    public static void main(String[] args) {
        Animal animal1 = new Animal(12, "dog", 500);
        Animal animal2 = new Animal(14, "cat", 600);
        System.out.println(animal1.getClass());
        System.out.println(animal2.getClass());
        Dog dog = new Dog();
        System.out.println(dog instanceof Animal);
        Animal animal = new Dog();
        Dog dog1 = (Dog) new Animal();

    }
}

class Dog extends Animal {

}

class Animal {
    int age;
    String name;
    double price;

    public Animal() {
    }

    public Animal(int age, String name, double price) {
        this.age = age;
        this.name = name;
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Animal animal = (Animal) o;
        return age == animal.age && Double.compare(price, animal.price) == 0 &&
                Objects.equals(name, animal.name);
    }
    public boolean equals2(Object o) {
        //1.判断是否同一个对象
        if (this == o) return true;
        //2.判断对象是否空或是否同一个类的对象
        if (o == null || this.getClass() != o.getClass()) return false;
        //3.强制转化为People类型
        Animal animal = (Animal) o;
        //4.判断两个对象的各个个属性是否都相同
        return this.age == animal.age && Objects.equals(this.name, animal.name) && this.price == animal.price;

    }


    @Override
    public int hashCode() {
        return Objects.hash(age, name, price);
    }

}
